<template>
  <div class='noticeManage' >
    <el-row class='first-title'>
      <div class="lf">
        <h3 class="">{{searchDeptCategory}}</h3>
      </div>
    </el-row>
    <el-row class="second-sec">
      <el-tabs v-model="tabActiveName" @tab-click='noticeTabClick'>
        <el-tab-pane label="发布公告" name="issue">
          <div class="issuePart">
            <div class="notice-title">
              <el-form :model="noticeForm">
                <el-row :gutter="20">
                  <el-col :span='6'>
                    <el-form-item label="类型：" class="formType">
                      <el-select v-model="noticeForm.type" placeholder="请选择类型">
                        <el-option
                          v-for="item in typeList"
                          :key="item.key"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span='14'>
                    <el-form-item label="标题：" class='titleItem'>
                      <el-input v-model="noticeForm.title_name" placeholder="请输入标题"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span='6'>
                    <el-form-item label="是否置顶：" class='titleItem'>
                      <el-checkbox label="" name="type" v-model="noticeForm.is_top"></el-checkbox>
                    </el-form-item>
                  </el-col>
                  <el-col :span='14'>
                    <el-form-item
                      label="置顶到期时间："
                      class='titleItem'
                      v-show="noticeForm.is_top">
                      <el-date-picker
                        type="datetime"
                        placeholder="选择日期时间"
                        v-model="noticeForm.top_end_time"
                        style="width: 100%;">
                      </el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="内容:" class='formContent'>
                  <Ueditor
                    @ready="editorReady"
                    :ueditorConfig='ueditorConfig'
                    style="display: inline-block;">
                  </Ueditor>
                </el-form-item>
                <el-form-item class="submitBts">
                  <el-button type="primary" @click="onSubmitNoticeForm">提交</el-button>
                  <el-button type="success" @click="onPreviewNoticeForm">预览</el-button>
                  <el-button @click="clearNoticeForm">重置</el-button>
                  <el-button
                    @click="onCancelEditNotice"
                    v-show="issueOrEdit === 'edit'? true: false">取消修改</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="管理公告" name="manage">
          <div class="managePart">
            <el-table
              :data="noticeTableData"
              border
              style="width: 100%">
              <el-table-column
                v-for='item in tableColumn'
                :key="item.prop"
                :prop="item.prop"
                :label="item.label"
                :width="item.width"
                :formatter="item.formatter">
              </el-table-column>
              <el-table-column
                label="操作"
                width="140">
                <template scope="scope">
                  <el-button
                    class="successBt"
                    @click="noticeLookClick(scope.row)"
                    type="text"
                    size="small">
                    查看
                  </el-button>
                  <el-button
                    @click="noticeEditClick(scope.row)"
                    type="text"
                    size="small">编辑</el-button>
                  <el-button
                    class="dangerBt"
                    @click="noticeDeleteClick(scope.row)"
                    type="text"
                    size="small">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="paginationDiv">
              <my-pagination
                :sizeChange='handleSizeChange'
                :currentChange='handleCurrentChange'
                :totals='pagination.total'>
              </my-pagination>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-row>
    <el-dialog
      title="查看"
      :visible.sync="lookDialogVisible"
      width="50%"
      :lock-scroll='false'
      class="lookModal">
      <div class="lookModalDiv">
        <div class="noticeTitle">
          <i class="isTop" v-if="lookNoticeData.is_top === 1? true: false">顶</i>
          {{lookNoticeData.title_name}}
          <span>({{lookNoticeData.author_time}})</span>
        </div>
        <div class="noticeSomething">
          <div>类型：<span>{{lookNoticeData.type === 1?'任免信息' : (lookNoticeData.type === 2 ? '公示信息' : '招聘信息')}}</span></div>
          <div v-if="lookNoticeData.is_top === 1? true: false">
            置顶到期时间：
            <span>{{lookNoticeData.top_end_time}}</span>
          </div>
        </div>
        <div>
          <div class="noticeContent" v-html="lookNoticeData.content"></div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="lookDialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="提示"
      :visible.sync="deleteDialogVisible"
      width="20%"
      :lock-scroll='false'>
      <div class="deleteModalCont">
        确定要删除吗?
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="deleteNotice">确 定</el-button>
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="提示"
      :visible.sync="cancelEditVisible"
      width="20%"
      :lock-scroll='false'>
      <div class="deleteModalCont">
        确定要取消修改吗?
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancelEditNotice">确 定</el-button>
        <el-button @click="cancelEditVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import Vue from 'vue'
  import Ueditor from '@/components/public/Ueditor'
  import myPagination from '@/components/public/pagination'
  import { Message, Select,Option,Input, Checkbox, DatePicker,Dialog, Col, Row,Tabs,TabPane,Table,TableColumn,Pagination} from 'element-ui' 
  // Vue.use(Message)
  Vue.use(Select)
  Vue.use(Option)
  Vue.use(Input)
  Vue.use(Checkbox)
  Vue.use(DatePicker)
  Vue.use(Dialog)
  Vue.use(Col)
  Vue.use(Row)
  Vue.use(Tabs)
  Vue.use(TabPane)
  Vue.use(Table)
  Vue.use(TableColumn)
  Vue.use(Pagination)

  export default {
    data() {
      return {
        searchDeptCategory:'通知公告管理',
        typeList: [
          {
            key: '1',
            label: '任免信息',
            value: 1
          },
          {
            key: '2',
            label: '公示信息',
            value: 2
          },{
            key: '2',
            label: '招聘信息',
            value: 3
          }
        ],
        tabActiveName: 'issue',
        issueOrEdit: 'issue',
        noticeForm: {
          type: '',
          title_name: '',
          is_top: '',
          top_end_time: '',
          content: ''
        },
        noticeTableData:[],
        noticeRowData:{},
        lookNoticeData:{},
        tableColumn: [
          {
            prop: 'index',
            label: '序号',
            width: '70'
          },
          {
            prop: 'type',
            label: '公告类型',
            width: '100',
            formatter:function(row, column, cellValue){
              if (cellValue === 1) {
                return '任免信息'
              }else if(cellValue === 2){
                return '公示信息'
              } else {
                return '招聘信息'
              }
            }
          },
          {
            prop: 'title_name',
            label: '标题',
            width: ''
          },
          {
            prop: 'author',
            label: '发布人',
            width: '120'
          },
          {
            prop: 'author_time',
            label: '发布日期',
            width: '120',
            formatter:function(row, column, cellValue){
              return cellValue.split(' ')[0]
            }
          },
          {
            prop: 'is_top',
            label: '是否置顶',
            width: '100',
            formatter:function(row, column, cellValue){
              if (cellValue === 1) {
                return '是'
              }else{
                return '否'
              }
            }
          }
        ],
        previewDialogVisible:false,
        lookDialogVisible:false,
        deleteDialogVisible:false,
        cancelEditVisible: false,
        pagination:{
          pageNum:1,
          pageSize:10,
          total:0
        },
        ueditorConfig:{
          initialFrameWidth :800,//设置编辑器宽度
          initialFrameHeight:400,//设置编辑器高度
          scaleEnabled:false,
          autoHeightEnabled: false,
          toolbars:[
            ['Undo','Redo','|',
          'Bold','Italic','Underline','StrikeThrough','Superscript','Subscript','RemoveFormat','FormatMatch','|',
          'BlockQuote','|',
          'PastePlain','|',
          'ForeColor','BackColor','InsertOrderedList','InsertUnorderedList','|',
          'Paragraph','RowSpacing','FontFamily','FontSize','|',
          'DirectionalityLtr','DirectionalityRtl','|','','Indent','Outdent','|',
          'JustifyLeft','JustifyCenter','JustifyRight','JustifyJustify','|',
          'Link','Unlink','Anchor','MultiMenu','Code', '|',
          'Horizontal','Date','Time','Spechars','|',
          'InsertTable','DeleteTable','InsertParagraphBeforeTable','InsertRow','DeleteRow','InsertCol','DeleteCol','MergeCells','MergeRight','MergeDown','SplittoCells','SplittoRows','SplittoCols','|',
          'SelectAll','ClearDoc']
          ]
        },
        editorInstance:null
      }
    },
    methods: {
      formatTableData:function(data){
        for(var i=0; i<data.length; i++){
          data[i].index=(i+1)+this.pagination.pageSize*(this.pagination.pageNum-1);
          data[i].title_name = data[i].title_name.replace('职位审批表','')
        }
        return data
      },
      formatDateTime:function(){
        Date.prototype.Format = function (fmt) {
          var o = {
              "M+": this.getMonth() + 1, //月份 
              "d+": this.getDate(), //日 
              "h+": this.getHours(), //小时 
              "m+": this.getMinutes(), //分 
              "s+": this.getSeconds(), //秒 
              "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
              "S": this.getMilliseconds() //毫秒 
          };
          if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
          for (var k in o)
          if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
          return fmt;
        }
      },
      getNowTime:function(){
        var d = new Date().Format("yyyy-MM-dd hh:mm:ss")
        return d
      },
      //ueditor的onready事件  这里获取ueditor的实例
      editorReady:function(instance){
        this.editorInstance = instance
      },
      getNoticeData:function(){
        var obj = {
          type:0,
          pageNum:this.pagination.pageNum,
          pageSize: this.pagination.pageSize
        }
        this.PostAjax('/announcement/queryMoreList',obj,this.getNoticeDataCB)
      },
      getNoticeDataCB:function(data){
        if (data.data.datas) {
          this.noticeTableData=this.formatTableData(data.data.datas)
          this.pagination.total=data.data.total
          console.log('getNoticeDataCB',this.noticeTableData)
        }
      },
      noticeTabClick:function(tab){
        var self = this
        if (this.issueOrEdit === 'edit'&& tab.name === 'manage') {
          setTimeout(function(){
            self.tabActiveName = 'issue'
          },200)
          this.cancelEditVisible = true
        }
      },
      onCancelEditNotice:function(){
        this.cancelEditVisible = true
      },
      cancelEditNotice:function(){
        this.cancelEditVisible = false
        this.tabActiveName = 'manage'
        this.issueOrEdit = 'issue'
        this.clearNoticeForm()
      },
      typeListOnChange:function(e){
        this.type = e
        switch(e){
          case 'dismiss':
            break;
          case 'notice':
            break;
          default:
            break;
        }
      },
      onSubmitNoticeForm:function(){
        var obj = {}
        this.noticeForm.content = this.editorInstance.getContent()
        obj = {
          type: this.noticeForm.type,
          titleName: this.noticeForm.title_name,
          isTop: this.noticeForm.is_top? 1 : 0,
          content: this.noticeForm.content
        }
        if (this.noticeForm.is_top) {
          if (typeof this.noticeForm.top_end_time === 'object') {
            obj.topEndTime = this.noticeForm.top_end_time.getTime()
          }else{
            obj.topEndTime = new Date(this.noticeForm.top_end_time).getTime()
          }
        }else{
          obj.topEndTime = ''
        }
        if (this.issueOrEdit === 'edit') {
          obj.id = this.noticeForm.id
        }
        this.PostAjax('/announcement/saveNotice',obj,this.submitNoticeFormCB)
      },
      submitNoticeFormCB:function(data){
        if (data.data.status === 1) {
          if (this.issueOrEdit === 'edit') {
            Message.success('修改成功!')
            this.tabActiveName = 'manage'
            this.issueOrEdit === 'issue'
          }else{
            Message.success('发布成功!')
          }
          this.getNoticeData()
          this.clearNoticeForm()
        }else{
          if (this.issueOrEdit === 'edit') {
            Message.error('修改失败!')
          }else{
            Message.error('发布失败!')
          }
        }
      },
      onPreviewNoticeForm:function(){
        var obj
        this.noticeForm.content = this.editorInstance.getContent()
        obj = JSON.parse(JSON.stringify(this.noticeForm))
        obj.is_top = obj.is_top? 1 : 0
        obj.author_time = this.getNowTime()
        this.lookNoticeData = obj
        this.lookDialogVisible = true
      },
      clearNoticeForm:function(){
        for(var key in this.noticeForm){
          this.noticeForm[key] = ''
        }
        this.editorInstance.setContent('')
      },
      noticeLookClick:function(row){
        this.lookDialogVisible = true
        this.lookNoticeData = JSON.parse(JSON.stringify(row))
      },
      noticeEditClick:function(row){
        this.tabActiveName = 'issue'
        this.issueOrEdit = 'edit'
        this.noticeForm = JSON.parse(JSON.stringify(row))
        this.noticeForm.is_top = this.noticeForm.is_top === 1? true : false
        this.editorInstance.setContent(this.noticeForm.content)
      },
      noticeDeleteClick:function(row){
        this.noticeRowData = JSON.parse(JSON.stringify(row))
        this.deleteDialogVisible = true
      },
      deleteNotice:function(){
        this.PostAjax('/announcement/deleteNotice',{id:''+this.noticeRowData.id},this.deleteNoticeCB)
      },
      deleteNoticeCB:function(data){
        if (data.data.status === 1) {
          this.deleteDialogVisible = false
          this.getNoticeData()
          Message.success('删除成功!')
        }else{
          Message.error('删除失败!')
        }
      },
      PostAjax:function(url,params,callback){
        var self = this;
        this.Axios.Post(url,params).then(function(res){
          if(callback){
            callback(res)
          }
        })
      },
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.pagination.pageSize=val
        this.getNoticeData()
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.pagination.pageNum=val
        this.getNoticeData()
      }
    },
    computed:{
    },
    created:function(){
      this.formatDateTime()
    },
    mounted: function () {
      this.getNoticeData()
    },
    beforeDestroy: function () {
      window.removeEventListener("scroll",this.scrollFunc);
    },
    components: {
      Ueditor,
      myPagination
    },
    watch:{
    },
    filters:{
    }
  }
</script>

<style scoped>
  .noticeManage .successBt{
    color: #13ce66;
  }
  .noticeManage .successBt:hover{
    color: #42d885;
  }
  .noticeManage .dangerBt{
    color: #ff4949;
  }
  .noticeManage .dangerBt:hover{
    color: #ff6d6d;
  }
  .noticeManage .first-title h3{
      font-size: 24px;
      margin-top: 20px;
      margin-bottom: 20px;
      font-weight: 500;
      line-height: 1.1;
  }
  .noticeManage .first-title h3 small{
    font-size: 65%;
    font-weight: normal;
    line-height: 1;
    color: #777;
    margin-left:5px;
  }
  .noticeManage .second-sec{
      position: relative;
      border-radius: 3px;
      background: #ffffff;
      border-top: 3px solid #d2d6de;
      margin-bottom: 20px;
      width: 100%;
      box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
      border-top-color: #00a65a;
      min-height: 420px;
  }
  .noticeManage .issuePart, .noticeManage .managePart{
    padding: 20px;
  }
  .noticeManage .notice-title{
    border-bottom: 1px solid #f4f4f4;
    padding:10px;
    overflow: hidden;
  }
  .noticeManage .sendBt{
    text-align: center;
    padding: 10px 0;
  }
  .noticeManage .paginationDiv{
    padding: 10px 0;
    margin-top: 20px;
  }
  .noticeManage .deleteModalCont{
    padding-left: 30px;
  }
  .noticeManage .lookModalDiv{
    padding: 0 10px;
  }
  .noticeManage .lookModal .noticeTitle{
    font-size: 20px;
    padding: 10px 0;
    color: #2544a7;
  }
  .noticeManage .lookModal i{
    display: inline-block;
    padding: 2px;
    background-color: #ff9800;
    color:#ffffff;
    font-size: 12px;
    font-style: normal;
    vertical-align: top;
  }
  .noticeManage .lookModal .noticeTitle span{
    font-size: 12px;
    padding: 0 5px;
    color: #999;
  }
  .noticeManage .lookModal .noticeSomething>div{
    display: inline-block;
    margin-right:30px;
  }
  .noticeManage .lookModal .noticeSomething>div>span{
    color:cornflowerblue;
  }
  .noticeManage .lookModal .noticeContent{
    padding-top:30px; 
  }
</style>
<style>
  /*修改element-ui样式*/
  .noticeManage .notice-title .el-select{
    width: 120px;
  }
  .noticeManage .notice-title .titleItem .el-input{
    width: 350px;
  }
  .noticeManage .notice-title .el-date-editor{
    width: 250px!important;
  }
  .noticeManage .submitBts .el-form-item__content{
    text-align: center;
  }
</style>
